﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Acms.Bll;

public partial class Templates_Home_Default : Acms.AcmsControls.TemplatePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            List<Post> posts = null;
            if (AcmsContext.CurrentPost != null)
            {
                posts = Acms.Bll.Post.GetAllBySiteIdAndParentPath(AcmsContext.SiteId, "~/Stores", AcmsContext.SiteVersion);
            }
            else
            {
                posts = Acms.Bll.DummyPost.CreateDummyList(15);
            }
            storeLocator.MaxHeight = Unit.Pixel(300);
            posts = posts.OrderBy(x => x.DisplayName).ToList();
            foreach (var post in posts)
            {
                var item = new Telerik.Web.UI.RadComboBoxItem();
                int? fileId = GetFileId(post);
                string storeName = GetStoreName(post);
                string barristaName = GetBarristaName(post);
                if (fileId.HasValue)
                    item.ImageUrl = string.Format("~/File.aspx?Id={0}&width=20&height=20", fileId);
                item.Text = string.Format("{0} - {1}", storeName, barristaName);
                item.Value = GetStoreUrl(post);
                storeLocator.Items.Add(item);
            }
        }
    }

    private string GetStoreUrl(Post post)
    {
        if (post is DummyPost)
        {
            return "#";
        }
        else
        {
            return ResolveUrl(post.Url);
        }
    }

    private string GetBarristaName(Post post)
    {
        if (post is DummyPost)
        {
            return "Barrista Name";
        }
        else
        {
            var nameControl = post.FindPostControl("Barrista Name");
            if (nameControl != null)
            {
                var nameProperties = nameControl.GetProperties<Acms.AcmsControls.TextContentControlProperties>();
                if (nameProperties != null)
                {
                    return nameProperties.Text;
                }
            }
            return null;
        }
    }

    private string GetStoreName(Post post)
    {
        if (post is DummyPost)
        {
            return "Store Name";
        }
        else
        {
            return post.DisplayName;
        }
    }

    private int? GetFileId(Post post)
    {
        if (post is DummyPost)
        {
            return -1;
        }
        else
        {
            return post.ThumbnailId;
        }
    }
}
